﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DemoWin
{
    /// <summary>
    /// Structural Communication Data  结构化通讯数据
    /// </summary>
    public class SCD
    {
        /// <summary>
        /// 初始化
        /// </summary>
        /// <param name="bData">源数据</param>
        public SCD(byte[] bData)
        {
            BYTES = bData;
            HEX = JConvert.BytesToHex(bData);
            HEAD = HEX.Substring(0, 2);
            ADDR = HEX.Substring(2, 8);
            CMD = HEX.Substring(10, 2);
            DATA = HEX.Substring(12, 112);
            CRC = HEX.Substring(124, 4);
        }

        /// <summary>
        /// 初始化
        /// </summary>
        /// <param name="head">包头 1字节，电脑to设备方向为0xfa,设备to电脑方向为0xfc。</param>
        /// <param name="cmd">命令码 1字节</param>
        /// <param name="data">数据包内容 56字节</param>
        public SCD(string head, string cmd, string data)
        {
            HEAD = head.Replace(" ", "").PadLeft(2, '0').Substring(0, 2);
            ADDR = "00000000"; // addr.Replace(" ", "").PadLeft(8, '0').Substring(0, 8);
            CMD = cmd.Replace(" ", "").PadLeft(2, '0').Substring(0, 2);
            DATA = data.Replace(" ", "").PadRight(112, '0').Substring(0, 112);
            CRC = JConvert.CRC16(ADDR + CMD + DATA);
            HEX = HEAD + ADDR + CMD + DATA + CRC;
            BYTES = JConvert.HexToBytes(HEX);
        }

        /// <summary>
        /// 完整Hex串
        /// </summary>
        public string HEX { get; }

        /// <summary>
        /// 完整Bytes串
        /// </summary>
        public byte[] BYTES { get; }

        /// <summary>
        /// 包头 1字节，电脑to设备方向为0xfa,设备to电脑方向为0xfc。
        /// </summary>
        public string HEAD { get; }

        /// <summary>
        /// 设备地址码 4字节，本公司产品的独一无二的身份信息。
        /// </summary>
        public string ADDR { get; }

        /// <summary>
        /// 命令码 1字节
        /// </summary>
        public string CMD { get; }

        /// <summary>
        /// 数据包内容 56字节
        /// </summary>
        public string DATA { get; }

        /// <summary>
        /// 校验码 2字节
        /// </summary>
        public string CRC { get; }
    }
}
